package org.jeecg.modules.gis.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.geotools.data.simple.SimpleFeatureSource;
import org.jeecg.modules.gis.mapper.DataManagerMapper;
import org.jeecg.modules.gis.service.IDataManagerService;
import org.jeecg.modules.gis.util.GisDbUtil;
import org.jeecg.modules.gis.util.ShapefileTableBuilder;
import org.jeecg.modules.gis.util.mybatis.GisBaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class DataManagerServiceImpl extends GisBaseServiceImpl implements IDataManagerService {
    @Autowired
    private DataManagerMapper dataManagerMapper;

    @Autowired
    private GisDbUtil gisDbUtil;  // 注入我们自己的工具类
    @Value("#{environment['spring.datasource.dynamic.datasource.master.url'] != null ? environment['spring.datasource.dynamic.datasource.master.url'] : environment['spring.datasource.url']}")
    private String url;

    private String getDmSchema(){
        Pattern pattern = Pattern.compile("schema=([^&]+)");
        Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return "";
    }
    public List<String> getGeomTables() {
        String dbType = gisDbUtil.getDbType(); // 这里调用自己的工具类获取数据库类型
        switch (dbType.toLowerCase()) {
            case "mysql":
                return dataManagerMapper.getMysqlTablesWithGeom();
            case "postgresql":
                return dataManagerMapper.getPostgresTablesWithGeom();
            case "oracle":
                return dataManagerMapper.getOracleTablesWithGeom();
            case "dm":
            case "dameng":
                return dataManagerMapper.getDmTablesWithGeom(getDmSchema());
            default:
                throw new UnsupportedOperationException("不支持的数据库类型: " + dbType);
        }
    }

    @Override
    @Transactional
    public void createTableByShp(SimpleFeatureSource source, String typeName) throws Exception {
        String sql = ShapefileTableBuilder.buildCreateTableSQL(source, typeName, gisDbUtil.getDbType());
        dataManagerMapper.createTableBySql(sql);
        List<String> insets = ShapefileTableBuilder.buildInsertSQL(source, typeName, gisDbUtil.getDbType());
        for (String insertSql : insets) {
            log.info("执行插入语句：{}", insertSql); // 使用占位符方式防止日志拼接性能问题
            dataManagerMapper.insertBySql(insertSql);
        }

    }


}
